﻿using ArchivesAdmin.Entity.StorageManage;
using ArchivesAdmin.Service.StorageManage;
using ArchivesAdmin.Util;
using ArchivesAdmin.Util.Model;
using ArchivesAdmin.Web.Code;
using System;
using System.Collections.Generic;

using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.OneD;
using ZXing.QrCode;
using ZXing.QrCode.Internal;

namespace ArchivesAdmin.Service
{
    public class PrinterHelper
    {
        static string CODE = "";
        static BarLibEntity ENTITY;
        static string STARDID;
        static string CHILDID;
        /// <summary>
        /// 打印标签条码
        /// </summary>
        /// <param name="code">盒码 or  箱码</param>
        public static void PrintLabel(BarLibEntity entity, string startId,string childId)
        {
            ENTITY = new BarLibEntity();
            ENTITY = entity;
            STARDID = startId;
            CHILDID = childId;
          //  AllARCHIVESID = allArchivesId;
            if (ENTITY.Boxcode != "Z")
            {
                CODE = entity.Boxcode;

                Task<OperatorInfo> user = Operator.Instance.Current();

                long curUserId = 0;
                if (user != null)
                {
                    curUserId = (long)user.Result.UserId;
                }
                else
                {
                    curUserId = 0;
                }

                //kg1： 326288780057120768   -  使用 Printer1
                //kg2： 326289605580034048   -  使用 Printer2
                //kg3： 326289913924292608   -  使用 Printer3
                string PrinterName = "";
                switch (curUserId)
                {
                    case 326288780057120768:
                        PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer1"];
                        break;
                    case 326289605580034048:
                        PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer2"];
                        break;
                    case 326289913924292608:
                        PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer3"];
                        break;
                }

                PrintDocument pd = new PrintDocument();
                pd.PrintPage += new PrintPageEventHandler(printDocument_PrintA4Page);

                pd.DefaultPageSettings.PrinterSettings.PrinterName = PrinterName;       //打印机名称
                                                                                        // 宽、高：百分之一英寸为单位 
                string PageSettingName = System.Configuration.ConfigurationManager.AppSettings["PageSettingName"];
                string LabelWidth = System.Configuration.ConfigurationManager.AppSettings["LabelWidth"];
                string LabelHeight = System.Configuration.ConfigurationManager.AppSettings["LabelHeight"];

                PaperSize ps = new PaperSize(PageSettingName, int.Parse(LabelWidth), int.Parse(LabelHeight));
                ps.RawKind = 120; //如果是自定义纸张，就要大于118

                pd.DefaultPageSettings.PaperSize = ps;

                //pd.DefaultPageSettings.Landscape = true;  //设置横向打印，不设置默认是纵向的
                pd.PrintController = new System.Drawing.Printing.StandardPrintController();
                pd.Print();
            }
        }


        public static void PrintLabel_Bin(BarLibEntity entity)
        {
            CODE = entity.Bincode;
            ENTITY = entity;
            Task<OperatorInfo> user = Operator.Instance.Current();

            long curUserId = 0;
            if (user != null)
            {
                curUserId = (long)user.Result.UserId;
            }
            else
            {
                curUserId = 0;
            }

            //kg1： 326288780057120768   -  使用 Printer1
            //kg2： 326289605580034048   -  使用 Printer2
            //kg3： 326289913924292608   -  使用 Printer3
            string PrinterName = "";
            switch (curUserId)
            {
                case 326288780057120768:
                    PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer1"];
                    break;
                case 326289605580034048:
                    PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer2"];
                    break;
                case 326289913924292608:
                    PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer3"];
                    break;
            }

            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(printDocument_PrintA4Page);

            pd.DefaultPageSettings.PrinterSettings.PrinterName = PrinterName;       //打印机名称
                                                                                    // 宽、高：百分之一英寸为单位 
            string PageSettingName = System.Configuration.ConfigurationManager.AppSettings["PageSettingName"];
            string LabelWidth = System.Configuration.ConfigurationManager.AppSettings["LabelWidth"];
            string LabelHeight = System.Configuration.ConfigurationManager.AppSettings["LabelHeight"];

            PaperSize ps = new PaperSize(PageSettingName, int.Parse(LabelWidth), int.Parse(LabelHeight));
            ps.RawKind = 120; //如果是自定义纸张，就要大于118

            pd.DefaultPageSettings.PaperSize = ps;

            //pd.DefaultPageSettings.Landscape = true;  //设置横向打印，不设置默认是纵向的
            pd.PrintController = new System.Drawing.Printing.StandardPrintController();
            pd.Print();
        }

        private static  void printDocument_PrintA4Page(object sender, PrintPageEventArgs e)
        {
            Font titleFont = new Font("黑体", 10, System.Drawing.FontStyle.Bold);//标题字体           
            Font fntTxt = new Font("宋体", 12, System.Drawing.FontStyle.Regular);//正文文字         
            Font fntTxt1 = new Font("宋体", 8, System.Drawing.FontStyle.Regular);//正文文字           
            System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷           
            System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Black);           //线条颜色         
               
            try
            {
                //  盒码 or  箱码
                string PointX = System.Configuration.ConfigurationManager.AppSettings["PointX"];
                string PointY = System.Configuration.ConfigurationManager.AppSettings["PointY"];
                e.Graphics.DrawString(CODE, titleFont, brush, new System.Drawing.Point(int.Parse(PointX), int.Parse(PointY)));

                ////  CODE 生成一维码
                Image barcode = CreateBarCode(CODE);  //条形码
             //  Image barcode = CreateQRCode(CODE);  // 二维码

                //条码打印到标签纸上的宽、高
                string BarPointWidth = System.Configuration.ConfigurationManager.AppSettings["BarPointWidth"];
                string BarPointHeight = System.Configuration.ConfigurationManager.AppSettings["BarPointHeight"];
                // 条码开始打印点
                string BarPointX = System.Configuration.ConfigurationManager.AppSettings["BarPointX"];
                string BarPointY = System.Configuration.ConfigurationManager.AppSettings["BarPointY"];
                //条码 宽度的缩放比例
                string BarCodeWidthScale = System.Configuration.ConfigurationManager.AppSettings["BarCodeWidthScale"]; 
                e.Graphics.ScaleTransform(float.Parse(BarCodeWidthScale) , 1.0F);
                e.Graphics.DrawImage(barcode,  int.Parse(BarPointX), int.Parse(BarPointY), int.Parse(BarPointWidth), int.Parse(BarPointHeight));


                // 关联档案号 列表 
                string arclist="";
                string[] childId;
                string ArcPointX = System.Configuration.ConfigurationManager.AppSettings["ArcPointX"];
                string ArcPointY = System.Configuration.ConfigurationManager.AppSettings["ArcPointY"];
                if (CODE.Contains("H"))
                {
                    string str1 = STARDID.Substring(STARDID.Length - 3);
                    string str2 = ENTITY.Archiveid.Substring(ENTITY.Archiveid.Length - 3);
                    if (ENTITY.Isscreenchildid == 1)
                    {
                        int i = int.Parse(str1); int j = int.Parse(str2);
                        int t = i;
                        childId = CHILDID.Split("/");
                        for (int k = 0; k < j - i + 1; k++)
                        {    
                            
                            arclist += t.ToString().PadLeft(2, '0') + " (" + childId[k].Substring(0,childId[k].Length-1)+")\n";                                                      
                            t++;
                            
                        }
                        e.Graphics.DrawString(arclist, fntTxt1, brush, new System.Drawing.Point(int.Parse(ArcPointX), int.Parse(ArcPointY)));

                    }
                    else
                    {
                        if (str1 != str2)
                            arclist = str1 + "~" + str2;
                        else
                            arclist = str1;
                        childId = CHILDID.Split("/");
                        if (childId[0] != "")
                            arclist += "\n(" + childId[0] + ")";                //例： 001~005\n(01;02;)
                        arclist=arclist.Substring(0,arclist.Length - 2)+")";    //去掉括号里最后的分号
                        e.Graphics.DrawString(arclist, fntTxt, brush, new System.Drawing.Point(int.Parse(ArcPointX), int.Parse(ArcPointY)));
                    }
                   
                   
                }
                else
                {
                    string str= ENTITY.Boxcode;
                    string[] s = str.Split(";");
                    if (s.Length != 2)
                        arclist = s[0].Substring(s[0].Length - 7) + "~" + s[s.Length - 2].Substring(s[0].Length - 7);
                    else
                        arclist = s[0].Substring(s[0].Length - 7);
                    e.Graphics.DrawString(arclist, fntTxt, brush, new System.Drawing.Point(int.Parse(ArcPointX), int.Parse(ArcPointY)));
                }
                }
            catch (Exception ee)
            {
                LogHelper.Write(ee.InnerException);
            }
        }
       

        #region 参考代码
        ///** @param context 尽量用activity,以防使用过屏幕适配工具类后application context 和activity里的desplaymetric里的dpidensity不一致
        // @param expectWidth 期望的宽度
        // @param maxWidth 最大允许宽度
        // * @param contents 生成条形码的内容
        // * @param height
        // * @return
        // */
        //public static Bitmap getBarCodeWithoutPadding( int expectWidth, int maxWidth, int heightExpect, String contents)
        //{ 
        //    int realWidth = getBarCodeNoPaddingWidth(expectWidth, contents, maxWidth);

        //    return SyncEncodeBarcode(contents, realWidth, heightExpect, 0);
        //}

        //// 计算生成无白边的宽度
        //private static int getBarCodeNoPaddingWidth(int expectWidth, String contents, int maxWidth)
        //{
        //    bool[] code = new Code128Writer().encode(contents);

        //    int inputWidth = code.Length;
        //    LogHelper.Write("code:" + contents + " code.length:" + inputWidth + " expectWidth:" + expectWidth + " maxWidth:" + maxWidth);

        //    //code:210000000000000082 code.length:134 expectWidth:397 maxWidth:435
        //    // Add quiet zone on both sides.
        //    //int fullWidth = inputWidth + 0;

        //    double outputWidth = (double)Math.Max(expectWidth, inputWidth);
        //    double multiple = outputWidth / inputWidth;
        //    LogHelper.Write("multiple:" + multiple);
        //    //multiple:2.962686567164179

        //    //优先取大的
        //    int returnVal = 0;
        //    int ceil = (int)Math.Ceiling(multiple);
        //    if (inputWidth * ceil <= maxWidth)
        //    {
        //        returnVal = inputWidth * ceil;
        //    }
        //    else
        //    {
        //        int floor = (int)Math.Floor(multiple);
        //        returnVal = inputWidth * floor;
        //    }

        //    LogHelper.Write("returnVal:" + returnVal);
        //    return returnVal;
        //}

        ///**
        // * 同步创建条形码图片
        // *
        // * @param content  要生成条形码包含的内容
        // * @param width    条形码的宽度，单位px
        // * @param height   条形码的高度，单位px
        // * @param textSize 字体大小，单位px，如果等于0则不在底部绘制文字
        // * @return 返回生成条形的位图
        // *
        // * 白边问题:
        // *   https://blog.csdn.net/sunshinwong/article/details/50156017
        // *已知高度,计算宽度:
        // *
        // */
        //private static Bitmap SyncEncodeBarcode(String content, int width, int height, int textSize)
        //{
        //    if (string.IsNullOrEmpty(content))
        //    {
        //        return null;
        //    }
        //    IDictionary<EncodeHintType, object>  hints = new Dictionary<EncodeHintType, object>();

        //    hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");
        //    hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //    hints.Add(EncodeHintType.MARGIN, 0);

        //    try
        //    {
        //        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, width, height, hints);
        //        int[] pixels = new int[width * height];
        //        for (int y = 0; y < height; y++)
        //        {
        //            for (int x = 0; x < width; x++)
        //            {
        //                if (bitMatrix.getRow(x, y))
        //                {
        //                    pixels[y * width + x] = (int) 0xff000000;
        //                }
        //                else
        //                {
        //                    pixels[y * width + x] = (int) 0xffffffff;
        //                }
        //            }
        //        }
        //        Bitmap bitmap = Bitmap.(width, height, Bitmap.ARGB_8888);
        //        bitmap.SetPixel(//(pixels, 0, width, 0, 0, width, height);
        //        if (textSize > 0)
        //        {
        //            bitmap = showContent(bitmap, content, textSize);
        //        }
        //        return bitmap;
        //    }
        //    catch (Exception e)
        //    {

        //    }

        //    return null;
        //}

        //dp与px转换的方法
        //public static int dip2px(Context context, float dipValue)
        //{
        //    final float scale = context.getResources().getDisplayMetrics().density;
        //    return (int)(dipValue * scale + 0.5f);
        //}

        //public static int px2dip(Context context, float pxValue)
        //{
        //    final float scale = context.getResource().getDisplayMetrics().density;
        //    return (int)(pxValue / scale + 0.5f);
        //}


        /// <summary>
        /// 删除默认对应的空白
        /// </summary>
        /// <param name="matrix"></param>
        /// <returns></returns>
        private static BitMatrix deleteWhite(BitMatrix matrix)
         {
             int[] rec = matrix.getEnclosingRectangle();
             int resWidth = rec[2] + 1;
             int resHeight = rec[3] + 1;
 
             BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
             resMatrix.clear();
             for (int i = 0; i<resWidth; i++)
             {
                 for (int j = 0; j<resHeight; j++)
                 {
                     if (matrix[i + rec[0], j + rec[1]])
                         resMatrix[i, j]=true;
                 }
             }
             return resMatrix;
         }

        #endregion

        private static Image CreateBarCode(string content)
        {
            IDictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>();

            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 生成的条形码无边距: ZXing先自动获取了一个Margin默认值10，然后查看hints参数集合中是否存在参数EncodeHintType.MARGIN，存在则替换默认值
            hints.Add(EncodeHintType.MARGIN, 0); 

            BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, 100, 25, hints);
            BitMatrix bm2 = deleteWhite(bm); //删除默认对应的空白

           Image bmap = ConvertBitMatrixToImage(bm2);
           //  bmap.Save("d:/" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".png") ;
            return bmap; 
        }

        private static Image ConvertBitMatrixToImage(BitMatrix bm)
        {
            int width = bm.Width;
            int height = bm.Height;
            var white = System.Drawing.ColorTranslator.FromHtml("0xFFFFFFFF");
            var black = System.Drawing.ColorTranslator.FromHtml("0xFF000000");
            System.Drawing.Bitmap bmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, bm[x, y] ? black : white);
                }
            }
            return bmap;
        }

        private static Image CreateQRCode(String contents) 
        {
            QrCodeEncodingOptions qrEncodeOption = new QrCodeEncodingOptions();
            qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式，否则读取'中文'乱码
            qrEncodeOption.Height = 60;
            qrEncodeOption.Width = 60;
            qrEncodeOption.Margin = 1; // 设置周围空白边距

            QRCodeWriter  wr = new  QRCodeWriter();
            BitMatrix bm = wr.encode(contents, BarcodeFormat.QR_CODE, 60, 60); // 二维码
           
            Image bmap = ConvertBitMatrixToImage(bm);

            return bmap;
            //string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\QR-" + this.ContentTxt.Text + ".jpg";
            //img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //Map<EncodeHintType, Object> hints = new Map<EncodeHintType, Object>();
            //hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //return new QRCodeWriter().encode(contents, BarcodeFormat.QR_CODE, 40, 40, hints);
        }
    }
}
